# -*- coding:utf-8 -*-
"""
五六财经
http://www.56cj.com/
"""

import requests
import re
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def post_html_text(url, data):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_zx(url, data):
    text = post_html_text(url, data)
    if not text:
        return None
    regex = re.compile(r'<b>(\d{4}-\d{2}-\d{2})</b>')
    dates = re.findall(regex, text)
    return dates


def get_dates_kx(url, data):
    text = post_html_text(url, data)
    if not text:
        return None
    regex = re.compile(r'<span >(\d{4}-\d{2}-\d{2})[\s\S]*?</span>')
    dates = re.findall(regex, text)
    return dates


def count_process_zx():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 0
    while a < 200:
        data = {
            'classid': '26',
            'pageall': a * 10
        }
        url = 'http://www.56cj.com/news/index/newslistmore.html'
        a += 1
        print('----五六财经资讯获取第{}页----'.format(a))
        dates = get_dates_zx(url, data)
        if not dates:
            continue
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1

        if d4 > 0:
            break
    return (d1, d2, d3)


def count_process_kx():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 0
    while 1:
        data = {
            'pageall': a * 10,
            'last_time': '2018-09-05'
        }
        url = 'http://www.56cj.com/flash/index/flashmore.html'
        a += 1
        print('----五六财经快讯获取第{}页----'.format(a))
        dates = get_dates_kx(url, data)
        if not dates:
            continue
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '五六财经'
    t1 = count_process_kx()
    t2 = count_process_zx()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
